import { Context } from 'koa';
import searchService from '../services/search.service';

/**
 * 搜索控制器
 * @description 处理搜索相关请求
 */
class SearchController {
  /**
   * 全文搜索
   * @param ctx Koa上下文
   */
  public async search(ctx: Context): Promise<void> {
    try {
      const { query, page = 1, pageSize = 10, sortBy = 'relevance', categoryId, tags } = ctx.query;
      
      // 解析标签
      let tagIds: number[] = [];
      if (tags && typeof tags === 'string') {
        tagIds = tags.split(',').map(id => parseInt(id, 10)).filter(id => !isNaN(id));
      }
      
      const result = await searchService.search({
        query: query as string,
        page: parseInt(page as string, 10),
        pageSize: parseInt(pageSize as string, 10),
        sortBy: sortBy as string,
        categoryId: categoryId as string,
        tagIds
      });
      
      ctx.status = 200;
      ctx.body = {
        code: 200,
        message: '搜索成功',
        data: result
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: error instanceof Error ? error.message : '搜索失败',
      };
    }
  }
  
  /**
   * 获取搜索建议
   * @param ctx Koa上下文
   */
  public async getSuggestions(ctx: Context): Promise<void> {
    try {
      const { query } = ctx.query;
      
      if (!query || typeof query !== 'string') {
        ctx.status = 400;
        ctx.body = {
          code: 400,
          message: '搜索关键词不能为空',
        };
        return;
      }
      
      const suggestions = await searchService.getSuggestions(query);
      
      ctx.status = 200;
      ctx.body = {
        code: 200,
        message: '获取搜索建议成功',
        data: suggestions
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        code: 500,
        message: error instanceof Error ? error.message : '获取搜索建议失败',
      };
    }
  }
}

export default new SearchController(); 